'use client';

// 分享码表格组件
// REF: API-SHARE189-004@v1.0

import React, { useState } from 'react';
import {
  Eye,
  RefreshCw,
  Download,
  Trash2,
  Loader2,
  AlertCircle,
  CheckCircle2
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';

import { ShareCode } from './types';
import { statusMap, formatBytes, formatDate } from './utils';

interface ShareCodeTableProps {
  shareList: ShareCode[];
  onViewDetail: (shareId: number) => void;
  onParse: (shareId: number) => void;
  onDelete: (shareId: number) => void;
  onImportToVirtualDisk: (shareId: number) => void;
}

export function ShareCodeTable({
  shareList,
  onViewDetail,
  onParse,
  onDelete,
  onImportToVirtualDisk
}: ShareCodeTableProps) {
  const [loadingStates, setLoadingStates] = useState<Record<string, boolean>>({});

  // 设置加载状态
  const setLoading = (shareId: number, action: string, loading: boolean) => {
    const key = `${shareId}-${action}`;
    setLoadingStates(prev => ({ ...prev, [key]: loading }));
  };

  // 获取加载状态
  const isLoading = (shareId: number, action: string) => {
    const key = `${shareId}-${action}`;
    return loadingStates[key] || false;
  };

  // 优化的查看详情处理
  const handleViewDetail = async (shareId: number) => {
    setLoading(shareId, 'view', true);
    try {
      await onViewDetail(shareId);
    } finally {
      setLoading(shareId, 'view', false);
    }
  };

  // 优化的解析处理
  const handleParse = async (shareId: number) => {
    setLoading(shareId, 'parse', true);
    try {
      await onParse(shareId);
    } finally {
      setLoading(shareId, 'parse', false);
    }
  };

  // 优化的删除处理
  const handleDelete = async (shareId: number) => {
    setLoading(shareId, 'delete', true);
    try {
      await onDelete(shareId);
    } finally {
      setLoading(shareId, 'delete', false);
    }
  };

  // 优化的导入处理
  const handleImport = async (shareId: number) => {
    setLoading(shareId, 'import', true);
    try {
      await onImportToVirtualDisk(shareId);
    } finally {
      setLoading(shareId, 'import', false);
    }
  };

  return (
    <TooltipProvider>
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>分享码</TableHead>
            <TableHead>描述</TableHead>
            <TableHead>状态</TableHead>
            <TableHead>文件信息</TableHead>
            <TableHead>创建时间</TableHead>
            <TableHead className="text-right">操作</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {shareList.map((share) => {
            const statusInfo = statusMap[share.status as keyof typeof statusMap];
            const StatusIcon = statusInfo.icon;
            
            return (
              <TableRow key={share.id}>
                <TableCell>
                  <div className="space-y-1">
                    <div className="font-mono text-sm">{share.shareCode}</div>
                    {share.accessCode && (
                      <div className="text-xs text-gray-500">
                        访问码: {share.accessCode}
                      </div>
                    )}
                  </div>
                </TableCell>
                <TableCell>
                  <div className="max-w-48 truncate" title={share.description}>
                    {share.description || '-'}
                  </div>
                </TableCell>
                <TableCell>
                  <Badge className={statusInfo.color}>
                    <StatusIcon className="h-3 w-3 mr-1" />
                    {statusInfo.text}
                  </Badge>
                </TableCell>
                <TableCell>
                  {share.shareInfo ? (
                    <div className="text-sm space-y-1">
                      <div className="font-medium">{share.shareInfo.title}</div>
                      <div className="text-gray-500">
                        {share.shareInfo.fileCount} 个文件 · {formatBytes(share.shareInfo.totalSize)}
                      </div>
                    </div>
                  ) : (
                    <span className="text-gray-400">-</span>
                  )}
                </TableCell>
                <TableCell>
                  <div className="text-sm text-gray-500">
                    {formatDate(share.createdAt)}
                  </div>
                </TableCell>
                <TableCell className="text-right">
                  <div className="flex items-center justify-end gap-1">
                    {/* 查看详情按钮 - 只在解析完成后可用 */}
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleViewDetail(share.id)}
                          disabled={isLoading(share.id, 'view') || (share.status !== 2 && share.status !== 4)}
                          className={`h-8 w-8 p-0 ${
                            share.status === 2 || share.status === 4 
                              ? 'text-blue-600 hover:text-blue-700 hover:bg-blue-50' 
                              : 'text-gray-400'
                          }`}
                        >
                          {isLoading(share.id, 'view') ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            <Eye className="h-4 w-4" />
                          )}
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>
                          {share.status === 2 || share.status === 4 
                            ? '查看解析结果' 
                            : '需要先解析分享码才能查看详情'
                          }
                        </p>
                      </TooltipContent>
                    </Tooltip>
                    
                    {/* 解析按钮 - 仅在待解析状态显示 */}
                    {share.status === 0 && (
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleParse(share.id)}
                            disabled={isLoading(share.id, 'parse')}
                            className="h-8 w-8 p-0 text-blue-600 hover:text-blue-700 hover:bg-blue-50"
                          >
                            {isLoading(share.id, 'parse') ? (
                              <Loader2 className="h-4 w-4 animate-spin" />
                            ) : (
                              <RefreshCw className="h-4 w-4" />
                            )}
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>
                          <p>解析分享码</p>
                        </TooltipContent>
                      </Tooltip>
                    )}
                    
                    {/* 重新解析按钮 - 解析失败时显示 */}
                    {share.status === 3 && (
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleParse(share.id)}
                            disabled={isLoading(share.id, 'parse')}
                            className="h-8 w-8 p-0 text-orange-600 hover:text-orange-700 hover:bg-orange-50"
                          >
                            {isLoading(share.id, 'parse') ? (
                              <Loader2 className="h-4 w-4 animate-spin" />
                            ) : (
                              <AlertCircle className="h-4 w-4" />
                            )}
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>
                          <p>重新解析</p>
                        </TooltipContent>
                      </Tooltip>
                    )}
                    
                    {/* 导入按钮 - 在解析完成和已导入状态都显示 */}
                    {(share.status === 2 || share.status === 4) && (
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleImport(share.id)}
                            disabled={isLoading(share.id, 'import')}
                            className={`h-8 w-8 p-0 ${
                              share.status === 4 
                                ? 'text-green-600 hover:text-green-700 hover:bg-green-50' 
                                : 'text-green-600 hover:text-green-700 hover:bg-green-50'
                            }`}
                          >
                            {isLoading(share.id, 'import') ? (
                              <Loader2 className="h-4 w-4 animate-spin" />
                            ) : (
                              <Download className="h-4 w-4" />
                            )}
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>
                          <p>{share.status === 4 ? '重新导入到虚拟网盘' : '导入到虚拟网盘'}</p>
                        </TooltipContent>
                      </Tooltip>
                    )}
                    
                    {/* 删除按钮 */}
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDelete(share.id)}
                          disabled={isLoading(share.id, 'delete')}
                          className="h-8 w-8 p-0 text-red-600 hover:text-red-700 hover:bg-red-50"
                        >
                          {isLoading(share.id, 'delete') ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            <Trash2 className="h-4 w-4" />
                          )}
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>删除分享码</p>
                      </TooltipContent>
                    </Tooltip>
                  </div>
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </TooltipProvider>
  );
}

export default ShareCodeTable;